<template>
  <div class="content" :class="{ 'is-mobile': isMobile }">
    <heads :current="1"></heads>
    <div class="main">
      <div class="order-container">
        <!-- Product Details Section -->
        <div class="product-section">
          <h1 class="product-title">{{ product.name }}</h1>
          <div class="product-gallery">
            <el-carousel :height="isMobile ? '250px' : '400px'" :autoplay="false">
              <el-carousel-item v-for="(image, index) in product.imageList" :key="index">
                <img :src="image" :alt="product.name" class="carousel-image">
              </el-carousel-item>
            </el-carousel>
            <!--            <div class="thumbnail-row" v-if="!isMobile">-->
            <!--              <div v-for="(image, index) in product.imageList"-->
            <!--                   :key="index"-->
            <!--                   class="thumbnail"-->
            <!--                   @click="currentIndex = index">-->
            <!--                <img :src="image" :alt="product.name">-->
            <!--              </div>-->
            <!--            </div>-->
          </div>
          <div class="product-info">
            <div class="price" style="color: #0F7CD0;font-weight: bold">价格：${{ product.price }}</div>
            <div class="details">
              <div class="detail-item">
                <span class="label">时长:</span>
                <span>{{ product.duration }}</span>
              </div>
              <div class="detail-item">
                <span class="label">位置:</span>
                <span>{{ product.location }}</span>
              </div>
              <div class="detail-item">
                <span class="label">产品编号:</span>
                <span>{{ product.code }}</span>
              </div>
            </div>
            <div v-html="product.content"></div>
          </div>
        </div>

        <!-- Booking Form Section -->
        <div class="booking-section">
          <div class="booking-form">
            <h2 class="form-title">开始预定</h2>

            <!-- Passenger Selection -->
            <div class="passenger-section">
              <h3>输入乘客 Passenger <span class="required">*</span></h3>
              <div class="passenger-type" v-for="type in passengerTypes" :key="type.id">
                <div class="type-label">
                  <span>{{ type.label }}</span>
                  <span class="price">${{ type.price }}</span>
                </div>
                <el-select v-model="type.count" class="count-select">
                  <el-option
                      v-if="n >= type.min && n <= type.max"
                      v-for="n in type.max"
                      :key="n"
                      :label="n"
                      :value="n">
                  </el-option>
                </el-select>
              </div>
            </div>

            <!-- Date Selection -->
            <div class="date-section">
              <h3>选择日期 <span class="required">*</span></h3>
              <el-calendar v-model="selectedDate" @change="changeDay">
                <template #dateCell="{ data }">
                  <div
                      class="calendar-cell"
                      :class="{
                      'is-selected': isSelected(data.day),
                      'is-disabled': isDateDisabled(data.day)
                    }"
                      @click.stop="handleDateClick(data.day)"
                  >
                    {{ data.day.split('-').slice(-1)[0] }}
                  </div>
                </template>
              </el-calendar>
            </div>

            <!-- Time Selection -->
            <div class="time-section">
              <h3>选择时间 <span class="required">*</span></h3>
              <div class="time-grid-container">
                <div v-if="availableTimes.length" class="time-grid">
                  <div
                      v-for="time in availableTimes"
                      :key="time.id"
                      class="time-cell"
                      :class="{
                      'booked': time.booked,
                      'selected': cycleId === time.id
                    }"
                      @click="handleTimeClick(time)"
                  >
                    <div class="time">{{ formatTime(time.start_time) }}</div>
                    <div class="seats">剩余: {{ time.count - time.orderList.length }}座</div>
                    <div class="status">
                      <span v-if="time.booked">已约</span>
                      <span v-else-if="cycleId === time.id">已选</span>
                      <span v-else>可约</span>
                    </div>
                  </div>
                </div>
                <div v-else class="empty-state">
                  暂无可约时段
                </div>
              </div>
            </div>

            <!-- Total Price -->
            <div class="total-price">
              <span>价格</span>
              <span class="amount">${{ totalPrice }}</span>
            </div>

            <!-- Submit Button -->
            <el-button
                v-if="!showPassengerForm"
                type="primary"
                class="submit-btn"
                :loading="submitting"
                :disabled="!cycleId"
                @click="confirmBooking"
            >
              确认预订
            </el-button>

            <!-- Passenger Information Form -->
            <div v-if="showPassengerForm" class="passenger-form">
              <h3>订单联系人</h3>
              <div class="contact-form">
                <el-form :model="contactPerson" :rules="rules" ref="contactForm">
                  <el-form-item prop="name" label="姓名">
                    <el-input v-model="contactPerson.name" placeholder="请输入联系人姓名"></el-input>
                  </el-form-item>

                  <el-form-item prop="phone" label="联系电话">
                    <el-input v-model="contactPerson.phone" placeholder="请输入联系电话"></el-input>
                  </el-form-item>

                  <el-form-item prop="email" label="电子邮箱">
                    <el-input v-model="contactPerson.email" placeholder="请输入电子邮箱"></el-input>
                  </el-form-item>

                  <el-form-item prop="wechat" label="微信号">
                    <el-input v-model="contactPerson.wechat" placeholder="请输入微信号（选填）"></el-input>
                  </el-form-item>
                  <el-form-item prop="wechat" label="备注">
                    <el-input
                        type="textarea"
                        v-model="contactPerson.notes"
                        placeholder="如有特殊需求请在此说明"
                        :rows="2">
                    </el-input>
                  </el-form-item>
                </el-form>
              </div>

              <!--              <h3>乘客信息</h3>-->
              <!--              <div v-for="(passenger, index) in passengerForms" :key="index" class="passenger-info">-->
              <!--                <div class="passenger-header">-->
              <!--                  <h4>乘客 {{ index + 1 }} ({{ passenger.type }})</h4>-->
              <!--                  <span class="required">*为必填项</span>-->
              <!--                </div>-->

              <!--                <el-form :model="passenger" :rules="passengerRules" :ref="'passengerForm' + index">-->
              <!--                  <el-form-item prop="name" label="姓名" required>-->
              <!--                    <el-input v-model="passenger.name" placeholder="请输入乘客姓名"></el-input>-->
              <!--                  </el-form-item>-->

              <!--                  <el-form-item prop="phone" label="联系电话" required>-->
              <!--                    <el-input v-model="passenger.phone" placeholder="请输入联系电话"></el-input>-->
              <!--                  </el-form-item>-->

              <!--                  <el-form-item prop="email" label="电子邮箱" required>-->
              <!--                    <el-input v-model="passenger.email" placeholder="请输入电子邮箱"></el-input>-->
              <!--                  </el-form-item>-->

              <!--                  <el-form-item prop="notes" label="备注">-->
              <!--                    <el-input-->
              <!--                      type="textarea"-->
              <!--                      v-model="passenger.notes"-->
              <!--                      placeholder="如有特殊需求请在此说明"-->
              <!--                      :rows="2">-->
              <!--                    </el-input>-->
              <!--                  </el-form-item>-->
              <!--                </el-form>-->
              <!--              </div>-->

              <!-- Payment Button -->
              <el-button
                  type="primary"
                  class="payment-btn"
                  @click="proceedToPayment"
                  :loading="submitting">
                立即支付
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
    <foot></foot>
  </div>
</template>

<script>
import { http } from '@/api/api.js'
import dayjs from "dayjs";

export default {
  name: 'order',
  data() {
    return {
      isMobile: false,
      product: {
        imageList: []
      },
      passengerTypes: [
        {
          id: 1,
          label: '成人 Adult',
          price: 0,
          count: 1,
          min: 1,
          max: 10
        },
        {
          id: 2,
          label: '儿童 Child',
          price: 0,
          count: 0,
          min: 0,
          max: 10
        }
      ],
      selectedDate: dayjs().add(1, 'day').toDate(), // 默认选择次日
      cycleId: '',
      submitting: false,
      currentIndex: 0,
      availableTimes: [],
      currentTimeSlot: null,
      showPassengerForm: false,
      passengerForms: [],
      contactPerson: {
        name: '',
        phone: '',
        email: '',
        wechat: '',
        notes: ''
      },
      rules: {
        // name: [
        //   { required: true, message: '请输入姓名', trigger: 'blur' }
        // ],
        // phone: [
        //   { required: true, message: '请输入电话号码', trigger: 'blur' }
        // ],
        // email: [
        //   { required: true, message: '请输入电子邮箱', trigger: 'blur' },
        //   { type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' }
        // ]
      },
      lastRequestedDate: ''
    }
  },
  computed: {
    totalPrice() {
      return this.passengerTypes.reduce((sum, type) => {
        return sum + (type.price * type.count)
      }, 0).toFixed(2)
    },
    remainingSeats() {
      if (!this.currentTimeSlot) return 0
      return this.currentTimeSlot.count - this.currentTimeSlot.orderList.length
    },
    adultMaxCount() {
      return this.remainingSeats
    },
    childMaxCount() {
      const remainingAfterAdults = this.remainingSeats - this.passengerTypes[0].count
      return Math.max(0, remainingAfterAdults)
    }
  },
  watch: {
    selectedDate: {
      handler(val, oldVal) {
        if (dayjs(val).format('YYYY-MM-DD') !== dayjs(oldVal).format('YYYY-MM-DD')) {
          this.changeDay(val)
          this.resetPassengerForm()
        }
      },
      immediate: true
    },
    cycleId: {
      handler(newId) {
        this.resetPassengerForm()
        // 更新当前时间段信息
        this.currentTimeSlot = this.availableTimes.find(t => t.id === newId) || null
        // 重置乘客数量
        if (this.currentTimeSlot) {
          const maxSeats = this.remainingSeats
          // 更新成人最大值
          this.passengerTypes[0].max = maxSeats
          // 如果当前选择的成人数超过最大值，调整为最大值
          if (this.passengerTypes[0].count > maxSeats) {
            this.passengerTypes[0].count = maxSeats
          }
          // 更新儿童最大值并调整当前值
          this.updateChildLimits()
        }
      }
    },
    'passengerTypes.0.count': {
      handler(newCount) {
        this.updateChildLimits()
      }
    }
  },
  methods: {
    updateChildLimits() {
      const childType = this.passengerTypes[1]
      childType.max = this.childMaxCount
      if (childType.count > childType.max) {
        childType.count = childType.max
      }
    },
    resetPassengerForm() {
      this.showPassengerForm = false
      this.passengerForms = []
      this.contactPerson = {
        name: '',
        phone: '',
        email: '',
        wechat: '',
        notes: ''
      }
    },

    updatePassengerForms() {
      // Create a new array to store updated passenger forms
      const newPassengerForms = []
      let totalIndex = 0

      // Iterate through passenger types
      this.passengerTypes.forEach(type => {
        for (let i = 0; i < type.count; i++) {
          // Find existing passenger form for this type and index
          const existingForm = this.passengerForms.find(form =>
              form.type === type.label &&
              form.typeIndex === i
          )

          if (existingForm) {
            // Keep existing data if form already exists
            newPassengerForms.push({
              ...existingForm,
              formIndex: totalIndex // Update form index for ref
            })
          } else {
            // Create new form if doesn't exist
            newPassengerForms.push({
              type: type.label,
              typeIndex: i,
              formIndex: totalIndex,
              name: '',
              phone: '',
              email: '',
              notes: ''
            })
          }
          totalIndex++
        }
      })

      // Update forms array
      this.passengerForms = newPassengerForms

      // Force re-render of forms
      this.$nextTick(() => {
        this.$forceUpdate()
      })
    },

    confirmBooking() {
      if (!this.validateForm()) return

      // Initialize passenger forms
      this.updatePassengerForms()
      this.showPassengerForm = true
    },

    changeDate(dateId) {
      let find = this.availableTimes.find(item => item.id === dateId)
      this.passengerTypes.forEach(item => {
        if (item.is_adult) {
          item.price = find.price
        } else {
          item.price = find.child_price
        }
      })
      this.resetPassengerForm()
    },
    async changeDay(date) {
      if (typeof date === 'string') {
        this.selectedDate = new Date(date)
      }
      // 避免重复请求
      const dateStr = dayjs(this.selectedDate).format('YYYY-MM-DD')
      if (this.lastRequestedDate === dateStr) return
      this.lastRequestedDate = dateStr
      // 清空周期id
      this.cycleId = ''
      await this.getAvailableTimes(dateStr)
    },
    async getAvailableTimes(date) {
      console.log('date', date)
      const response = await http.shipCycle.list({
        ship_id: this.$route.query.id,
        start_time: date
      })
      this.availableTimes = response.data.filter(item => {
        return item.orderList.length < item.count
      })
      if (this.availableTimes.length) {
        this.cycleId = this.availableTimes[0].id
        this.changeDate(this.cycleId)
      } else {
        this.cycleId = ''
        this.passengerTypes.forEach(item => {
          item.price = 0
        })
        this.resetPassengerForm()
      }
    },
    checkDevice() {
      this.isMobile = window.innerWidth <= 750
    },
    isSelected(day) {
      if (!this.selectedDate) return false
      return dayjs(day).format('YYYY-MM-DD') === dayjs(this.selectedDate).format('YYYY-MM-DD')
    },
    isDateDisabled(day) {
      const tomorrow = dayjs().add(1, 'day').startOf('day')
      return dayjs(day).isBefore(tomorrow)
    },

    handleDateClick(day) {
      if (this.isDateDisabled(day)) return
      this.selectedDate = new Date(day)
      this.changeDay(day)
    },

    async proceedToPayment() {
      // Validate contact form first
      try {
        await this.$refs.contactForm.validate()
      } catch (error) {
        return
      }

      // Validate all passenger forms
      // for (let i = 0; i < this.passengerForms.length; i++) {
      //   try {
      //     await this.$refs[`passengerForm${i}`][0].validate()
      //   } catch (error) {
      //     return
      //   }
      // }

      this.submitting = true
      try {
        let count = 0
        let userList = []
        this.passengerTypes.forEach(item => {
          for (let i = 0; i < item.count; i++) {
            userList.push({
              is_adult: item.is_adult,
            })
            count++
          }
        })
        const orderData = {
          ship_id: this.$route.query.id,
          cycle_id: this.cycleId,
          contact_name: this.contactPerson.name,
          contact_phone: this.contactPerson.phone,
          contact_email: this.contactPerson.email,
          contact_wx: this.contactPerson.wechat,
          contact_remark: this.contactPerson.notes,
          totalPrice: this.totalPrice,
          amount: this.totalPrice,
          userList: userList,
          count
        }

        const response = await http.order.create('', orderData)
        this.$router.push({
          path: '/payment',
          query: {orderId: response.data.id}
        })
      } catch (error) {
        this.$message.error('创建订单失败，请重试')
      } finally {
        this.submitting = false
      }
    },
    validateForm() {
      if (this.passengerTypes.every(type => type.count === 0)) {
        this.$message.warning('请选择至少一位乘客')
        return false
      }
      if (!this.cycleId) {
        this.$message.warning('请选择行程时间')
        return false
      }
      return true
    },
    handleTimeClick(time) {
      if (time.booked) return
      this.cycleId = time.id
      this.changeDate(time.id)
    },
    formatTime(timeStr) {
      return dayjs(timeStr).format('HH:mm')
    },
  },
  async created() {
    try {
      console.log('-----')
      const {data: product} = await http.ship.read(this.$route.query.id)
      this.product = {
        ...product,
        imageList: (product.images || '').split(',')
      }
      console.log('product', product)
      // 根据产品价格设置乘客类型
      if (product.price) {
        this.passengerTypes[0].price = product.price
      }

      if (product.child_price) {
        this.passengerTypes[1].price = product.child_price
      }
      await this.changeDay(this.selectedDate)
    } catch (error) {
      console.error('Error fetching product:', error)
      this.$message.error('获取产品信息失败')
    }
  },
  mounted() {
    this.checkDevice()
    window.addEventListener('resize', this.checkDevice)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.checkDevice)
  }
}
</script>

<style lang="less" scoped>
.content {
  .main {
    padding: 20px;
    max-width: 1200px;
    margin: 0 auto;

    @media screen and (max-width: 750px) {
      padding: 10px;
    }
  }
}

.order-container {
  display: flex;
  gap: 30px;
  @media screen and (max-width: 750px) {
    flex-direction: column;
    gap: 20px;
  }
}

.product-section {
  flex: 1;

  .product-title {
    font-size: 24px;
    margin-bottom: 20px;

    @media screen and (max-width: 750px) {
      font-size: 20px;
      margin-bottom: 15px;
    }
  }

  .product-gallery {
    margin-bottom: 20px;

    .carousel-image {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }

    .thumbnail-row {
      display: flex;
      gap: 10px;
      margin-top: 10px;
      overflow-x: auto;
      padding-bottom: 5px;

      &::-webkit-scrollbar {
        height: 4px;
      }

      &::-webkit-scrollbar-thumb {
        background: #ddd;
        border-radius: 2px;
      }

      .thumbnail {
        flex-shrink: 0;
        width: 80px;
        height: 60px;
        cursor: pointer;
        opacity: 0.7;
        transition: opacity 0.3s;

        &:hover {
          opacity: 1;
        }

        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }
      }
    }
  }

  .product-info {
    .price {
      font-size: 20px;
      color: #333;
      margin-bottom: 15px;

      @media screen and (max-width: 750px) {
        font-size: 18px;
        margin-bottom: 10px;
      }
    }

    .details {
      .detail-item {
        margin-bottom: 10px;

        .label {
          color: #666;
          margin-right: 10px;
        }
      }
    }
  }
}

.booking-section {
  width: 100%;
  max-width: 420px;

  @media screen and (max-width: 750px) {
    max-width: none;
  }

  .booking-form {
    background: #fff;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);

    @media screen and (max-width: 750px) {
      padding: 15px;
      border-radius: 0;
      box-shadow: none;
      background: #f8f8f8;
    }

    .form-title {
      font-size: 20px;
      margin-bottom: 20px;
      text-align: center;

      @media screen and (max-width: 750px) {
        font-size: 18px;
        margin-bottom: 15px;
      }
    }

    .required {
      color: #ff4949;
    }

    h3 {
      margin-bottom: 15px;
      font-size: 16px;
    }
  }

  .passenger-section {
    margin-bottom: 20px;

    .passenger-type {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 10px;

      .type-label {
        flex: 1;
        display: flex;
        justify-content: space-between;
        margin-right: 15px;

        .price {
          color: #666;
        }
      }

      .count-select {
        width: 100px;
      }
    }
  }

  .date-section {
    margin-bottom: 20px;

    :deep(.el-calendar) {
      --el-calendar-selected-bg-color: #0F7CD0;
      --el-calendar-selected-color: #fff;

      .el-calendar__body {
        padding: 8px;

        .el-calendar-day {
          padding: 0;
          height: 36px;
        }

        td {
          border: none;
        }
      }

      .el-calendar-table {
        tr {
          td {
            &:first-child {
              border-left: none;
            }

            &:last-child {
              border-right: none;
            }
          }
        }
      }
    }

    .calendar-cell {
      height: 36px;
      width: 100%;
      margin: 0 auto;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 14px;
      transition: all 0.3s ease;
      cursor: pointer;

      &.is-selected {
        background-color: #0F7CD0;
        color: #fff;
      }

      &.is-disabled {
        color: #ccc;
        cursor: not-allowed;
        background-color: #f5f5f5;
      }

      &:hover:not(.is-disabled) {
        background-color: #0F7CD0;
        color: #fff;
      }
    }
  }

  .time-section {
    margin-bottom: 20px;

    .time-grid-container {
      margin-top: 15px;
    }

    .time-grid {
      display: grid;
      grid-template-columns: repeat(4, 1fr);
      gap: 10px;

      @media screen and (max-width: 750px) {
        grid-template-columns: repeat(3, 1fr);
      }
    }

    .time-cell {
      background-color: #f8f8f8;
      padding: 10px;
      border-radius: 8px;
      cursor: pointer;
      text-align: center;
      transition: all 0.3s ease;

      &.booked {
        background-color: #f5f5f5;
        cursor: not-allowed;
        opacity: 0.7;

        .status, .seats {
          color: #999;
        }
      }

      &.selected {
        background-color: #0F7CD0;
        color: #fff;

        .status, .seats {
          color: #fff;
        }
      }

      .time {
        font-size: 14px;
        font-weight: bold;
        margin-bottom: 4px;
      }

      .seats {
        font-size: 12px;
        color: #666;
        margin-bottom: 4px;
      }

      .status {
        font-size: 12px;
        color: #666;
      }

      &:hover:not(.booked) {
        transform: translateY(-2px);
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      }
    }

    .empty-state {
      text-align: center;
      padding: 20px;
      background-color: #f8f8f8;
      border-radius: 8px;
      color: #666;
    }
  }

  .total-price {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin: 20px 0;
    padding: 15px 0;
    border-top: 1px solid #eee;
    border-bottom: 1px solid #eee;

    .amount {
      font-size: 20px;
      font-weight: bold;
      color: #333;
    }
  }

  .submit-btn {
    width: 100%;
    height: 44px;
    background-color: #0F7CD0;
    border: none;
    color: #fff;
    font-size: 16px;

    &:hover {
      background-color: darken(#0F7CD0, 5%);
    }

    &:not(:disabled):hover {
      background-color: #1989fa;
      border-color: #1989fa;
    }

    &:disabled {
      background-color: #a0cfff;
      border-color: #a0cfff;
      cursor: not-allowed;
    }
  }

  .passenger-form {
    margin-top: 30px;

    h3 {
      font-size: 18px;
      margin-bottom: 20px;
      padding-bottom: 10px;
      border-bottom: 1px solid #eee;

      &:not(:first-child) {
        margin-top: 40px;
      }
    }

    .contact-form {
      background: #f8f8f8;
      border-radius: 8px;
      padding: 20px;
      margin-bottom: 20px;

      :deep(.el-form-item) {
        margin-bottom: 20px;

        &:last-child {
          margin-bottom: 0;
        }

        .el-form-item__label {
          color: #666;
        }

        .el-input__inner {
          border-color: #dcdfe6;
        }
      }
    }

    .passenger-info {
      margin-bottom: 30px;
      padding: 20px;
      background: #f8f8f8;
      border-radius: 8px;

      .passenger-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;

        h4 {
          font-size: 16px;
          color: #333;
        }

        .required {
          font-size: 12px;
          color: #f56c6c;
        }
      }

      :deep(.el-form-item) {
        margin-bottom: 20px;

        .el-form-item__label {
          color: #666;
        }

        .el-input__inner {
          border-color: #dcdfe6;
        }
      }
    }

    .payment-btn {
      width: 100%;
      height: 44px;
      margin-top: 20px;
      background-color: #0F7CD0;
      border-color: #0F7CD0;

      &:hover {
        background-color: darken(#0F7CD0, 5%);
        border-color: darken(#0F7CD0, 5%);
      }
    }
  }

  .is-mobile {
    .contact-form {
      padding: 15px;
    }

    .passenger-info {
      padding: 15px;
    }
  }
}
</style>

<style>
.el-calendar-table .el-calendar-day {
  padding: 0 !important;
}

.el-calendar__body {
  padding: 0 !important;
}

.el-calendar__button-group {
  display: none !important;
}
</style>
